# -*- coding: utf-8 -*-
# @Author : zhaochen
# @Date   : 2019/6/17
# @File   : R15_IC_AccOvduCntLoansAndCreditAndQuasiTwentyFourMonsCheckOne_XD.py
# @E-mail : zhaochen@bbdservice.com

'''eof
name:申请人近2年内逾期天数在30天（含）以内的贷款、贷记卡及准贷记卡累计逾期次数校验
code:R15_IC_AccOvduCntLoansAndCreditAndQuasiTwentyFourMonsCheckOne_XD_2D
tableName:
columnName:
groups:个人征信校验
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import re
import datetime
import pandas as pd

reload(sys)
sys.setdefaultencoding('utf-8')

import json

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None:
            return [{}]
        elif table == "":
            return ""
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)
    if occurTimes == 1:
        if table == "":
            return ""
        elif table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)


def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def date_format(time):
    try:
        import re
        import datetime
        r1 = re.compile(u'年|月|日')
        time = r1.sub('.', time)
        try:
            date = datetime.datetime.strptime(time, '%Y.%m.%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y-%m-%d')
            except:
                try:
                    date = datetime.datetime.strptime(time, '%Y/%m/%d')
                except:
                    try:
                        r = re.compile(r'\D+')
                        tmp = r.sub('', time)
                        if len(tmp) > 8:
                            tmp = tmp[:8]
                        date = datetime.datetime.strptime(tmp, '%Y%m%d')
                    except:
                        date = None
        return date
    except:
        return None

def checkNull(data,data1, accountType):
    '''若最近24个月还款状态信息为空，返回结果为缺失值，则进行以下逻辑判断：
1.基本信息段（PD01A）-账户类型（PD01AD01）为D1，若最新表现信息段（PD01B）-账户状态（PD01BD01）为3（结清）且关闭日期（PD01BR01）＞5年或账户状态（PD01BD01）为5（转出）且转出月份（PD01BR04）＞5年，则Factor=1,否则Factor=缺失值；
2.基本信息段（PD01A）-账户类型（PD01AD01）为R1,R4，若最新表现信息段（PD01B）-账户状态（PD01BD01）为3（结清）且关闭日期（PD01BR01）＞5年，则Factor=1,否则Factor=缺失值；
3.基本信息段（PD01A）-账户类型（PD01AD01）为R2，R3，若最新表现信息段（PD01B）-账户状态（PD01BD01）为4(销户)且关闭日期（PD01BR01）＞5年或账户状态（PD01BD01）为6(未激活)，则Factor=1,否则Factor=缺失值；
当个人征信数据中账户状态（PD01BD01）为空时，取最近一次月度表现信息段（PD01CD01）;
'''
    if data in null_type_list or data == [{}] or data == 0:
        return 0
    if data1 in null_type_list or data1 == [{}] or data1 == 0:
        PD01CD01 =None
    else:
        PD01CD01 = data1[0].get("PD01CD01")
    # 账户状态
    PD01BD01 = data[0].get("PD01BD01")
    # 关闭日期
    PD01BR01 = data[0].get("PD01BR01")
    PD01BR01 = dateFormat(PD01BR01)
    # 转出月份
    PD01BR04 = data[0].get("PD01BR04")
    PD01BR04 = dateFormat(PD01BR04)
    fiveYearsAgo = (datetime.datetime.now() - pd.tseries.offsets.DateOffset(years=5)).strftime("%Y%m")
    if accountType == "D1":
        if PD01BD01 not in null_type_list:
            if (PD01BD01 == "3" and PD01BR01 is not None and PD01BR01.strftime("%Y%m") <= fiveYearsAgo) \
                    or (PD01BD01 == "5" and PD01BR04 is not None and PD01BR04.strftime("%Y%m") <= fiveYearsAgo):
                return 1
            else:
                return 0
        else:
            if (PD01CD01 is not None and PD01CD01 == "3" and PD01BR01 is not None and PD01BR01.strftime("%Y%m") <= fiveYearsAgo) \
                    or (PD01CD01 is not None and PD01CD01 == "5" and PD01BR04 is not None and PD01BR04.strftime("%Y%m") <= fiveYearsAgo):
                return 1
            else:
                return 0
    elif accountType in ["R1", "R4"]:
        if PD01BD01 not in null_type_list:
            if (PD01BD01 == "3" and PD01BR01 is not None and PD01BR01.strftime("%Y%m") <= fiveYearsAgo):
                return 1
            else:
                return 0
        else:
            if (PD01CD01 is not None and PD01CD01 == "3" and PD01BR01 is not None and PD01BR01.strftime("%Y%m") <= fiveYearsAgo):
                return 1
            else:
                return 0
    elif accountType in ["R2", "R3"]:
        if PD01BD01 not in null_type_list:
            if (PD01BD01 == "4" and PD01BR01 is not None and PD01BR01.strftime("%Y%m") <= fiveYearsAgo) \
                    or (PD01BD01 == "6") or (PD01BD01 == "3"):
                return 1
            else:
                return 0
        else:
            if (PD01CD01 is not None and PD01CD01 == "4" and PD01BR01 is not None and PD01BR01.strftime("%Y%m") <= fiveYearsAgo) \
                    or (PD01CD01 == "6") or (PD01CD01 == "3"):
                return 1
            else:
                return 0

    else:
        return 0

def dateFormat(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d')
                except:
                    date = None
    return date

# 获取 上次申请时间
def get_relative_date():
    relative_date = ratingRequest.get('relativeDate')
    return date_format(relative_date)
# 计算24个月记录和5年逾期记录
def R15_IC_AccOvduCntLoansAndCreditAndQuasiTwentyFourMonsCheckOne():
    data = IC_DSJ_2D['data']
    factor = []
    # 借贷账户信息
    PDA = getTable(data, 'PDA', 1)
    if PDA is None:
        return u'缺失值'
    elif PDA == "":
        return 1
    else:
        # 借贷账户信息单元
        PD01 = getTable(PDA[0], 'PD01', 0)
        if PD01 is None or PD01 == "":
            return u'缺失值'
        elif PD01 == [{}]:
            return 1
        else:
            relative_date = get_relative_date()
            if relative_date is None:
                raise ValueError(u"网贷传输的数据字段relativeDate缺失或不符合要求")
            relative_date_month = relative_date.year * 12 + relative_date.month

            for i in PD01:
                try:
                    # 基本信息段
                    PD01A = getTable(i, 'PD01A', 1)
                    # 最近 24 个月还款记录信息段
                    PD01D = getTable(i, 'PD01D', 0)
                    # 最新表现信息段
                    PD01B = getTable(i, 'PD01B', 1)
                    # 最近一次月度表现信息段
                    PD01C = getTable(i, 'PD01C', 0)
                    # 最近5年内历史表现信息段
                    PD01E = getTable(i, 'PD01E', 0)
                    if PD01A is None or PD01A == "":
                        factor.append(None)
                    elif (PD01D is None or PD01D == "") and (PD01E is None or PD01E == ""):
                        factor.append(None)
                    else:
                        if PD01D is not None and PD01D != "" and PD01D != [{}]:
                            # 账户类型
                            PD01AD01 = PD01A[0].get('PD01AD01')
                            if PD01AD01 in null_type_list:
                                factor.append(None)
                            # D1(非循环贷账户),R1(循环贷账户),R2(贷记卡),R4(循环额度下分账户)
                            elif PD01AD01 in ['D1', 'R1', 'R2', 'R4']:
                                if PD01D == [{}]:
                                    factor.append(0)
                                else:
                                    # 还款状态信息
                                    PD01DH = getTable(PD01D[0], 'PD01DH', 1)
                                    if PD01DH is None or PD01DH == '':
                                        factor.append(None)
                                    else:
                                        for PD01DH_Itmes in PD01DH:
                                            # 还款状态
                                            PD01DD01 = PD01DH_Itmes.get('PD01DD01')
                                            # 月份
                                            PD01DR03 = PD01DH_Itmes.get('PD01DR03')
                                            if PD01DD01 in null_type_list or PD01DR03 in null_type_list:
                                                factor.append(None)
                                            else:
                                                PD01DR03_month = float(PD01DR03[:4]) * 12 + float(PD01DR03[5:7])
                                                if isfloat(PD01DD01) and float(PD01DD01) >=1 and float(PD01DD01) <=7 \
                                                        and PD01DR03_month > relative_date_month:
                                                    factor.append(float(PD01DD01))
                                                else:
                                                    factor.append(0)
                            # 准贷记卡
                            elif PD01AD01 == 'R3':
                                if PD01D == [{}]:
                                    factor.append(0)
                                else:
                                    # 还款状态信息
                                    PD01DH = getTable(PD01D[0], 'PD01DH', 1)
                                    if PD01DH is None or PD01DH == '':
                                        factor.append(None)
                                    else:
                                        for PD01DH_Itmes in PD01DH:
                                            # 还款状态
                                            PD01DD01 = PD01DH_Itmes.get('PD01DD01')
                                            # 月份
                                            PD01DR03 = PD01DH_Itmes.get('PD01DR03')
                                            if PD01DD01 in null_type_list or PD01DR03 in null_type_list:
                                                factor.append(None)
                                            else:
                                                PD01DR03_month = float(PD01DR03[:4]) * 12 + float(PD01DR03[5:7])
                                                if isfloat(PD01DD01) and float(PD01DD01) >=3 and  float(PD01DD01) <= 7\
                                                        and PD01DR03_month > relative_date_month:
                                                    factor.append(float(PD01DD01) - 2)
                                                else:
                                                    factor.append(0)
                            else:
                                factor.append(0)
                        else:
                            if PD01E is None or PD01E == "" or PD01B is None or PD01B == "":
                                factor.append(None)
                            else:
                                # 账户类型
                                PD01AD01 = PD01A[0].get('PD01AD01')
                                if PD01AD01 in null_type_list:
                                    factor.append(None)
                                # D1(非循环贷账户),R1(循环贷账户),R2(贷记卡),R4(循环额度下分账户)
                                elif PD01AD01 in ['D1', 'R1', 'R2', 'R4']:
                                    if PD01E == [{}]:
                                        factor.append(0)
                                    else:
                                        # 历史表现信息
                                        PD01EH = getTable(PD01E[0], 'PD01EH', 1)
                                        if PD01EH is None or PD01EH == "":
                                            checkRes = checkNull(PD01B, PD01C,PD01AD01)
                                            if checkRes:
                                                factor.append(0)
                                            else:
                                                factor.append("None")
                                        else:
                                            for PD01EH_Itmes in PD01EH:
                                                # 还款状态
                                                PD01ED01 = PD01EH_Itmes.get('PD01ED01')
                                                # 月份
                                                PD01ER03 = PD01EH_Itmes.get('PD01ER03')
                                                if PD01ED01 in null_type_list or PD01ER03 in null_type_list:
                                                    factor.append(None)
                                                else:
                                                    PD01ER03_month = float(PD01ER03[:4]) * 12 + float(PD01ER03[5:7])
                                                    if isfloat(PD01ED01) and float(PD01ED01) >=1 and float(PD01ED01) <=7 \
                                                            and PD01ER03_month > relative_date_month:
                                                        factor.append(float(PD01ED01))
                                                    else:
                                                        factor.append(0)
                                # 准贷记卡
                                elif PD01AD01 == 'R3':
                                    if PD01E == [{}]:
                                        factor.append(0)
                                    else:
                                        # 历史表现信息
                                        PD01EH = getTable(PD01E[0], 'PD01EH', 1)
                                        if PD01EH is None or PD01EH == "":
                                            checkRes = checkNull(PD01B,PD01C, PD01AD01)
                                            if checkRes:
                                                factor.append(0)
                                            else:
                                                factor.append("None")
                                        else:
                                            for PD01EH_Itmes in PD01EH:
                                                # 还款状态
                                                PD01ED01 = PD01EH_Itmes.get('PD01ED01')
                                                # 月份
                                                PD01ER03 = PD01EH_Itmes.get('PD01ER03')
                                                if PD01ED01 in null_type_list or PD01ER03 in null_type_list:
                                                    factor.append(None)
                                                else:
                                                    PD01ER03_month = float(PD01ER03[:4]) * 12 + float(PD01ER03[5:7])
                                                    if isfloat(PD01ED01) and float(PD01ED01) >=3 and float(PD01ED01) <=7 \
                                                            and PD01ER03_month > relative_date_month:
                                                        factor.append(float(PD01ED01)-2)
                                                    else:
                                                        factor.append(0)
                                else:
                                    factor.append(0)
                except:
                    factor.append(None)
                    continue
    if "None" in factor:
        return u"缺失值"
    factorNotNone = filter(lambda x: x is not None, factor)
    factorNotNoneNotZero = filter(lambda x: x != 0, factorNotNone)
    if len(factorNotNone) == 0:
        return u'缺失值'
    elif len(factorNotNoneNotZero) == 0:
        return 1
    elif len(factorNotNoneNotZero) > 4 or max(factorNotNoneNotZero) > 1:
        return 0
    else:
        return 1

# 仅使用5年逾期记录计算
def R15_IC_AccOvduCntLoansAndCreditAndQuasiTwentyFourMonsCheckOne2():
    data = IC_DSJ_2D['data']
    factor = []
    # 借贷账户信息
    PDA = getTable(data, 'PDA', 1)
    if PDA is None:
        return u'缺失值'
    elif PDA == "":
        return 1
    else:
        # 借贷账户信息单元
        PD01 = getTable(PDA[0], 'PD01', 0)
        if PD01 is None or PD01 == "":
            return u'缺失值'
        elif PD01 == [{}]:
            return 1
        else:
            relative_date = get_relative_date()
            if relative_date is None:
                raise ValueError(u"网贷传输的数据字段relativeDate缺失或不符合要求")
            relative_date_month = relative_date.year * 12 + relative_date.month

            for i in PD01:
                try:
                    # 基本信息段
                    PD01A = getTable(i, 'PD01A', 1)
                    # 最新表现信息段
                    PD01B = getTable(i, 'PD01B', 1)
                    # 最近一次月度表现信息段
                    PD01C = getTable(i, 'PD01C', 0)
                    # 最近5年内历史表现信息段
                    PD01E = getTable(i, 'PD01E', 0)
                    if PD01A is None or PD01A == "":
                        factor.append(None)
                    elif PD01E is None or PD01E == "":
                        factor.append(None)
                    elif PD01E == [{}]:
                        factor.append(0)
                    else:
                        if PD01B is None or PD01B == "":
                            factor.append(None)
                        else:
                            # 账户类型
                            PD01AD01 = PD01A[0].get('PD01AD01')
                            if PD01AD01 in null_type_list:
                                factor.append(None)
                            # D1(非循环贷账户),R1(循环贷账户),R2(贷记卡),R4(循环额度下分账户)
                            elif PD01AD01 in ['D1', 'R1', 'R2', 'R4']:
                                if PD01E == [{}]:
                                    factor.append(0)
                                else:
                                    # 历史表现信息
                                    PD01EH = getTable(PD01E[0], 'PD01EH', 1)
                                    if PD01EH is None or PD01EH == "":
                                        checkRes = checkNull(PD01B,PD01C, PD01AD01)
                                        if checkRes:
                                            factor.append(0)
                                        else:
                                            factor.append("None")
                                    else:
                                        for PD01EH_Itmes in PD01EH:
                                            # 还款状态
                                            PD01ED01 = PD01EH_Itmes.get('PD01ED01')
                                            # 月份
                                            PD01ER03 = PD01EH_Itmes.get('PD01ER03')
                                            if PD01ED01 in null_type_list or PD01ER03 in null_type_list:
                                                factor.append(None)
                                            else:
                                                PD01ER03_month = float(PD01ER03[:4]) * 12 + float(PD01ER03[5:7])
                                                if isfloat(PD01ED01) and float(PD01ED01) >= 1 and float(
                                                        PD01ED01) <= 7 \
                                                        and PD01ER03_month > relative_date_month:
                                                    factor.append(float(PD01ED01))
                                                else:
                                                    factor.append(0)
                            # 准贷记卡
                            elif PD01AD01 == 'R3':
                                if PD01E == [{}]:
                                    factor.append(0)
                                else:
                                    # 历史表现信息
                                    PD01EH = getTable(PD01E[0], 'PD01EH', 1)
                                    if PD01EH is None or PD01EH == "":
                                        checkRes = checkNull(PD01B,PD01C, PD01AD01)
                                        if checkRes:
                                            factor.append(0)
                                        else:
                                            factor.append("None")
                                    else:
                                        for PD01EH_Itmes in PD01EH:
                                            # 还款状态
                                            PD01ED01 = PD01EH_Itmes.get('PD01ED01')
                                            # 月份
                                            PD01ER03 = PD01EH_Itmes.get('PD01ER03')
                                            if PD01ED01 in null_type_list or PD01ER03 in null_type_list:
                                                factor.append(None)
                                            else:
                                                PD01ER03_month = float(PD01ER03[:4]) * 12 + float(PD01ER03[5:7])
                                                if isfloat(PD01ED01) and float(PD01ED01) >= 3 and float(
                                                        PD01ED01) <= 7 \
                                                        and PD01ER03_month > relative_date_month:
                                                    factor.append(float(PD01ED01) - 2)
                                                else:
                                                    factor.append(0)
                            else:
                                factor.append(0)
                except:
                    factor.append(None)
                    continue
    if len(list(set(factor))) == 1 and list(set(factor))[0] == 'None':
        return u'缺失值'
    factorNotNone = [i for i in factor if i is not None and i != 'None']
    factorNotNoneNotZero = filter(lambda x: x != 0, factorNotNone)
    if len(factorNotNone) == 0:
        return u'缺失值'
    elif len(factorNotNoneNotZero) == 0:
        return 1
    elif len(factorNotNoneNotZero) > 4 or max(factorNotNoneNotZero) > 1:
        return 0
    else:
        return 1


result = R15_IC_AccOvduCntLoansAndCreditAndQuasiTwentyFourMonsCheckOne2()



